package com.greenline.pay.web.common.pipeline;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.greenline.framework.mursi.web.module.security.AbstractSecurity;
import com.greenline.framework.mursi.web.module.security.AuthorizationModule;
import com.greenline.framework.mursi.web.module.security.AuthorizationResult;
import com.greenline.framework.mursi.web.module.security.AuthorizationResult.ResultEnum;

public class AuthorizationValve extends AbstractSecurity implements AuthorizationModule {

    // private static final Log log =
    // LogFactory.getLog(AuthorizationValve.class);

    private String loginPath;

    private String expiredPath;

    @Override
    public AuthorizationResult isPermitted(HttpServletRequest request, HttpServletResponse response) {

        AuthorizationResult result = new AuthorizationResult();
        result.setResult(ResultEnum.OK);

        return result;
    }

    protected String getloginPathUrl(HttpServletRequest request) {
        StringBuffer url = request.getRequestURL();

        if (StringUtils.isNotEmpty(request.getQueryString())) {
            url.append("?");
            url.append(request.getQueryString());
        }
        try {
            String strUrl = url.toString();
            String t = request.getParameter("target");
            if (strUrl.indexOf(loginPath) > -1) {
                return loginPath;
            } else if (t == null || t.isEmpty()) {
                return loginPath + "?target=" + URLEncoder.encode(strUrl, "utf-8");
            }
            return loginPath;
        } catch (UnsupportedEncodingException e) {
            return loginPath;
        }
    }

    public void setExpiredPath(String expiredPath) {
        this.expiredPath = expiredPath;
    }

    /**
     * @param loginPath the loginPath to set
     */
    public void setLoginPath(String loginPath) {
        this.loginPath = loginPath;
    }

}
